<template>
  <div class="post-page w-100 d-flex flex-column align-items-center" v-if="currentPost">
    <modal :visible="modalVisible" :title="'删除文章'" @modal-on-close="modalClose" @modal-on-confirm="modalConfirm">
      <p>确定要删除这边文章吗</p>
    </modal>
    <div class="post-container w-50">
      <img :src="currentPost.image && currentPost.image.url" class="w-100 rounded-2" />
      <h2 class="my-4">{{ currentPost.title }}</h2>
      <author-info :author="author" :date="currentPost.createdAt"></author-info>
      <article v-html="currentHTML"></article>
    </div>
    <div v-if="showEditArea" class="w-50 mt-2">
      <router-link :to="{ name: 'create', query: { id: currentPost._id } }">
        <div class="btn btn-success">编辑</div>
      </router-link>
      <div class="btn btn-danger" @click="handleDeleteClick">删除</div>
    </div>
  </div>
</template>
<script lang="ts">
import { useStore } from 'vuex'
import { computed, defineComponent, onMounted, ref } from 'vue'
import { useRoute } from 'vue-router'
import { PostProps, GlobalProps, UserProps } from '../store'
import AuthorInfo from '../components/AuthorInfo.vue'
import MarkdownIt from 'markdown-it'
import Modal from '../components/Modal.vue'

export default defineComponent({
  components: {
    AuthorInfo,
    Modal
  },
  setup () {
    const store = useStore<GlobalProps>()
    const route = useRoute()
    const md = new MarkdownIt()
    onMounted(() => {
      store.dispatch('fetchPost', route.params.id)
    })
    const currentPost = computed<PostProps>(() => {
      return store.getters.getPostByCid(route.params.id)
    })
    const author = computed(() => {
      if (typeof currentPost.value.author === 'string') {
        return {
          _id: currentPost.value.author
        }
      }
      return currentPost.value.author
    })
    const showEditArea = computed<boolean>(() => {
      const { isLogin, _id } = store.state.user
      if (currentPost.value && currentPost.value.author && isLogin) {
        const postAuthor = currentPost.value.author as UserProps
        return postAuthor._id === _id
      }
      return false
    })
    const currentHTML = computed(() => {
      const { content, isHTML } = currentPost.value
      if (currentPost.value && content) {
        return isHTML ? content : md.render(content)
      } else {
        return md.render('')
      }
    })
    const modalVisible = ref(false)
    const handleDeleteClick = () => {
      modalVisible.value = true
    }
    const modalClose = () => {
      modalVisible.value = false
    }
    const modalConfirm = () => {
      modalVisible.value = false
    }
    return {
      currentPost,
      currentHTML,
      showEditArea,
      author,
      handleDeleteClick,
      modalVisible,
      modalClose,
      modalConfirm
    }
  }
})
</script>
